using UnityEngine;
using UnityEditor;
using UnityToolbarExtender;
using System.Linq;
using UnityEditor.SceneManagement;

[InitializeOnLoad]
public class SceneSwitchLeftButton
{
    static Texture2D _textureScene;
    static Texture2D _textureRefresh;

    // static bool m_enabled;
    // static bool Enabled
    // {
    //     get { return m_enabled; }
    //     set
    //     {
    //         m_enabled = value;
    //         EditorPrefs.SetBool("SceneViewFocuser", value);
    //     }
    // }

    static SceneSwitchLeftButton()
    {
        _textureScene = EditorGUIUtility.FindTexture("d_Scene");
        _textureRefresh = EditorGUIUtility.FindTexture("refresh");
        ToolbarExtender.LeftToolbarGUI.Add(OnLeftToolbarGUI);
        ToolbarExtender.RightToolbarGUI.Add(OnRightToolbarGUI);

        // m_enabled = EditorPrefs.GetBool("SceneViewFocuser", false);
        // EditorApplication.playModeStateChanged += OnPlayModeChanged;
        // EditorApplication.pauseStateChanged += OnPauseChanged;
    }

    static void OnLeftToolbarGUI()
    {
        GUILayout.FlexibleSpace();
        if (GUILayout.Button(new GUIContent(_textureRefresh, "重新开始游戏"), EditorStyles.toolbarButton, GUILayout.Width(30)))
        {
            EditorApplication.isPlaying = false;

            //暂时不清楚这里为啥必须要等2帧才能执行isPlaying = true有效
            EditorApplication.delayCall += () =>
            {
                EditorApplication.update -= DelayReStart;
                EditorApplication.update += DelayReStart;
            };
        }
    }

    static void DelayReStart()
    {
        if (!EditorApplication.isPlaying)
        {
            EditorApplication.update -= DelayReStart;
            EditorApplication.isPlaying = true;
        }
    }

    static void OnRightToolbarGUI()
    {
        var firstScene = EditorBuildSettings.scenes.First();
        var isOpendedScene = EditorSceneManager.GetActiveScene().path == firstScene.path;
        EditorGUI.BeginDisabledGroup(isOpendedScene);
        {
            if (GUILayout.Button(new GUIContent(_textureScene, "回到第一个场景"), EditorStyles.toolbarButton, GUILayout.Width(30)))
            {
                AssetDatabase.OpenAsset(AssetDatabase.LoadAssetAtPath<Object>(firstScene.path));
                // SceneHelper.StartScene(firstScene.path);
            }

            // DrawFocuse();
            GUILayout.FlexibleSpace();
        }
        EditorGUI.EndDisabledGroup();
    }

    // static void OnPauseChanged(PauseState obj)
    // {
    //     if (Enabled && obj == PauseState.Unpaused)
    //     {
    //         // Not sure why, but this must be delayed
    //         EditorApplication.delayCall += EditorWindow.FocusWindowIfItsOpen<SceneView>;
    //     }
    // }

    // static void OnPlayModeChanged(PlayModeStateChange obj)
    // {
    //     if (Enabled && obj == PlayModeStateChange.EnteredPlayMode)
    //     {
    //         EditorWindow.FocusWindowIfItsOpen<SceneView>();
    //     }
    // }

    // static void DrawFocuse()
    // {
    //     var tex = EditorGUIUtility.IconContent(@"UnityEditor.SceneView").image;

    //     GUI.changed = false;

    //     GUILayout.Toggle(m_enabled, new GUIContent(null, tex, "Focus SceneView when entering play mode"), EditorStyles.toolbarButton, GUILayout.Width(30));
    //     if (GUI.changed)
    //     {
    //         Enabled = !Enabled;
    //     }
    // }

    // static class SceneHelper
    // {
    //     static string sceneToOpen;

    //     public static void StartScene(string sceneName)
    //     {
    //         if (EditorApplication.isPlaying)
    //         {
    //             EditorApplication.isPlaying = false;
    //         }

    //         sceneToOpen = sceneName;
    //         EditorApplication.update += OnUpdate;
    //     }

    //     static void OnUpdate()
    //     {
    //         if (sceneToOpen == null ||
    //             EditorApplication.isPlaying || EditorApplication.isPaused ||
    //             EditorApplication.isCompiling || EditorApplication.isPlayingOrWillChangePlaymode)
    //         {
    //             return;
    //         }

    //         EditorApplication.update -= OnUpdate;

    //         if (EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo())
    //         {
    //             // need to get scene via search because the path to the scene
    //             // file contains the package version so it'll change over time
    //             string[] guids = AssetDatabase.FindAssets("t:scene " + sceneToOpen, null);
    //             if (guids.Length == 0)
    //             {
    //                 Debug.LogWarning("Couldn't find scene file");
    //             }
    //             else
    //             {
    //                 string scenePath = AssetDatabase.GUIDToAssetPath(guids[0]);
    //                 EditorSceneManager.OpenScene(scenePath);
    //                 EditorApplication.isPlaying = true;
    //             }
    //         }
    //         sceneToOpen = null;
    //     }
    // }
}